<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>阿新脚本-fetch</title>
  <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <style>
    body,
    div {
      margin: 0;
      padding: 0;
    }

    .rxui {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 12px;
    }

    .rxui_content {
      padding: 10px;
      overflow: hidden;
    }

    .rxui_title {
      font-weight: bold;
    }

    .rxui_input {
      margin: 20px 0;
    }

    .rxui_input_content {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-bottom: 15px;
    }

    .rxui_input_content:last-child {
      margin-bottom: 0;
    }

    .rxui_input .ric_des {
      margin-right: 5px;
    }

    .rxui_input .div_input {
      flex: 1;
      margin-right: 5px;
      min-width: 20px;
    }

    .rxui_buttons {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .rxui_button {
      margin-right: 30px;
      padding: 5px 10px;
    }

    .rxui_button:last-child {
      margin-right: 0;
    }

    .des {
      margin-top: 30px;
      background-color: azure;
    }

    .des span {
      font-size: 10px;
    }
  </style>

<body>
  <div class="rxui">
    <div class="rxui_content">
      <div class="rxui_title">欢迎使用 <阿新更新> [源码]</div>
      <div class="rxui_input">
        <div>更新源:</div>
        <div class="rxui_input_content">
          <div class="ric_des">[必填] url:</div>
          <textarea type="text" name="i_url" class="div_input" id="rx_input_url" row="5"
            placeholder="请输入api网址,不知的 请联系作者"></textarea>
          <button id="btn_input_clear_url">清除</button>
        </div>
      </div>

      <div class="rxui_buttons rx_no_select">
        <button id="btn_cancel" class="rxui_button">取消</button>
        <button id="btn_update" class="rxui_button rxui_button_confim">检查更新</button>
      </div>

      <div class="des">
        <div>上次更新</div>
        <span id="lastTime">
          --
        </span>
      </div>

      <div class="des">
        <div>根据固定 api网址，进行文件检查</div>
        <span>
          1. 将最新文件下载到 `res/folder`<br>
          2. 解压后，删除原有的 `main.lua`<br>
          3. 删除下载文件<br>
          <br>
          文件更新信息: `res/update/update.txt`
        </span>
        <div></div>
      </div>
    </div>
  </div>


  <script>
    // 设置 配置 文件命
    var ShowUIConfig = 'RxUpdate_0_1.dat'
  </script>

  <script>
    // 请求工具
    function requestBase(url, options = {}) {
      const defaultOption = {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        }
      }

      const data = options.body
      let method = options.method || ''
      method = method.toUpperCase()
      if (method) {
        options.method = method
      }
      if (data && method == 'POST') {
        if (typeof data != 'string') {
          // 这个是 fetch 的 body
          const dataString = JSON.stringify(data) || ''
          options.body = dataString
          defaultOption.headers['Content-Length'] = dataString.length
        } else {
          defaultOption.headers['Content-Length'] = data.length
        }
      }

      const fetchOptions = Object.assign({}, defaultOption, options)

      return fetch(url, fetchOptions).then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
      }).catch(error => {
        console.error('Fetch error:', error);
        throw error;
      });
    }

    function requestGet(ApiUrl, data = {}) {
      let url = ApiUrl
      if (data) {
        url += '?'
        let i = 0
        for (const key of Object.keys(data)) {
          if (i > 0) {
            url += '&'
          }
          url += '' + key + '=' + data[key]
        }
      }
      return requestBase(url)
    }

    function requestPost(ApiUrl, data) {
      const options = {
        method: 'POST',
        body: data
      }
      return requestBase(ApiUrl, options)
    }

    function baseRequestPostData(data) {
      data = data || {}
      return data
    }

    // ----- 按钮点击 确认
    function post_confirm(data) {
      const dataString = baseRequestPostData(data)
      console.log('点击 确认按钮 /set_event showUI_commit')
      return requestPost(
        '/set_event', // postApi
        {
          name: 'showUI_commit',
          value: dataString
        }
      )
    }

    // ----- 按钮点击 取消
    function post_cancel() {
      console.log('点击 取消按钮 /set_event showUI_cancel')
      return requestPost(
        '/set_event',
        { name: 'showUI_cancel' }
      )
    }

    // --- 获取 缓存
    function post_get_cache() {
      console.log('获取 缓存=> /load_file')
      // alert('获取 缓存 ShowUIConfig=' + ShowUIConfig)
      return requestPost(
        '/load_file',
        { name: ShowUIConfig }
      )
    }

    // --- 保存 缓存
    function post_save_cache(data) {
      const dataString = baseRequestPostData(data)
      console.log('保存 缓存=> /save_file')
      // alert('保存 缓存 ShowUIConfig=' + ShowUIConfig)
      return requestPost(
        '/save_file',
        {
          name: ShowUIConfig,
          data: dataString
        }
      )
    }
  </script>

  <script>
    function getBtnInputUrl() {
      return document.getElementById('rx_input_url')
    }

    // function getBtnInputPs() {
    //   return document.getElementById('rx_input_ps')
    // }

    function getSpanLastTime() {
      return document.getElementById('lastTime')
    }

    // 按钮点击
    function btnOnClick(btnId, cb) {
      document.getElementById(btnId).onclick = function () {
        cb && cb()
      }
    }

    // 点击取消
    btnOnClick('btn_cancel', () => post_cancel())

    // 点击确定
    btnOnClick('btn_update', () => {
      const input = getBtnInputUrl()
      const iv = input.value || ''
      const v = iv.trim() || ''

      if (!v) {
        alert('请输入正确的 api网址')
        return
      }

      if (v.indexOf('http') !== 0) {
        alert('请输入正确的 api网址')
        return
      }

      if (v.length < 11) {
        alert('请输入正确的 api网址')
        return
      }

      const data = { url: v, lastTime: '' }
      console.log('确认按钮 data=', data)
      post_save_cache(data).then((res) => {
        // alert('保存缓存 res=' + JSON.stringify(res || {}))
        post_confirm(data).then((res2) => {
          // alert('确认按钮 res2=' + JSON.stringify(res || {}))
        }).catch(error => {
          alert('确认按钮 error\n' + error.toString())
        })
      }).catch(error => {
        alert('保存缓存 error\n' + error.toString())
      })
    })

    btnOnClick('btn_input_clear_url', () => {
      const inputUrl = getBtnInputUrl()
      inputUrl.value = ''
    })

    // btnOnClick('btn_input_clear_ps', () => {
    //   const inputPs = getBtnInputPs()
    //   inputPs.value = ''
    // })
  </script>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      getCacheConfigFn();
    })

    function getCacheConfigFn() {
      console.log('获取缓存')
      post_get_cache().then((text) => {
        // alert('没有数据 text='+JSON.stringify(text || {}))
        /*
          text = {
            data: ___,
            success: true/false,
            message: ___
          }
         */
        let textObj = text
        if (text && typeof text === 'string') {
          try {
            textObj = JSON.parse(text) || {}
          } catch (error) {
            textObj = text
          }
        }

        if (textObj && typeof textObj == 'object') {
          // alert('数据 11 textObj obj str='+JSON.stringify(textObj || {}))
          let url = ''
          let ps = ''
          let lastTime = '--'
          let tdata = textObj.data || {}
          const succ = textObj.success || false
          const message = textObj.message || ''
          if (succ) {
            if (tdata && typeof tdata === 'string') {
              tdata = JSON.parse(tdata)
            }

            url = tdata.url || ''
            lastTime = tdata.lastTime || '--'
          } else {
            alert(message)
          }
          const inputUrl = getBtnInputUrl()
          inputUrl.value = url

          const spanLastTime = getSpanLastTime()
          spanLastTime.value = lastTime
        } else {
          alert('没有数据 22 textObj str=', JSON.stringify(textObj || {}))
        }
      }).catch(error => {
        alert('获取缓存 error\n' + error.toString())
      })

      // var browserVersion = getBrowserVersion();
      // alert('browser=' + browserVersion.browser + ' ' + browserVersion.version);
    }
  </script>

  <script>
    function getBrowserVersion() {
      var ua = navigator.userAgent;
      var browser = {
        isIe: /Trident\/(\d+)/.exec(ua),
        isEdge: /Edge\/(\d+)/.exec(ua),
        isChrome: /Chrome\/(\d+)/.exec(ua),
        isSafari: /Version\/(\d+)\.(\d+)(?:.\d+)? Safari\/|\((iP.*?)\)/i.exec(ua),
        isFirefox: /Firefox\/(\d+)/.exec(ua),
        isOpera: /Opera\/(\d+)/.exec(ua)
      };

      // 检测特定的浏览器并返回版本号
      for (var key in browser) {
        if (browser[key] && browser[key].length > 1) {
          return {
            browser: key,
            version: browser[key][1]
          };
        }
      }

      return { browser: 'unknown', version: 'unknown' };
    }
  </script>

</body>
</html>